from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from werkzeug.utils import redirect

from info import constants, db
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.modules.profile import profile_blu
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    """他人用户信息"""
    print(101)
    user = g.user
    # 获取参数
    other_id = request.args.get("user_id")
    page = request.args.get("p", None)

    # 校验参数
    if not other_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        other_id = int(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 根据id获取他人信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)
    is_followed = False
    if user and other:
        if other in user.followed:
            is_followed = True
    # 获取新闻
    if page:
        try:
            page = int(page)
        except Exception as e:
            current_app.logger.error(e)
    other_news = []
    current_page = 1
    total_page = 1
    # 查询用户发表的新闻
    try:
        paginate = News.query.filter(News.user_id == other_id).paginate(page, 2, False)
        other_news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    other_dict_li = []
    for othernew in other_news:
        other_dict_li.append(othernew.to_dict())

    data = {
        "other_info": other.to_dict(),
        "is_followed": is_followed,
        "user": g.user.to_dict() if g.user else None,
        "other_news": other_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("news/other.html", data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    """我的关注"""
    # 获取用户信息
    user = g.user
    # 获取参数,页数
    page = request.args.get("p", 1)
    # 校验参数
    if not page:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    follows = []
    current_page = 1
    total_page = 1
    # 根据参数化查询关注的用户信息
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        follows = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    user_dict_li = []
    for follow in follows:
        user_dict_li.append(follow.to_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "users": user_dict_li
    }

    return render_template("news/user_follow.html", data=data)


@profile_blu.route('/news_list')
@user_login_data
def user_news_list():
    """用户新闻列表"""
    # 获取页数
    page = request.args.get("p", 1)
    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    # 查询数据
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_list": news_dict_li
    }
    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/news_release', methods=["get", "post"])
@user_login_data
def news_release():

    user = g.user
    if request.method == "GET":
        # 查询新闻分类
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())
        # 移除最新这个分类
        category_dict_li.pop(0)
        data = {"categories": category_dict_li}
        return render_template('news/user_news_release.html', data=data)
    else:
        # 表示要发布新闻
        # 获取参数
        print(999)
        source = "个人发布"  # 新闻来源
        title = request.form.get("title")
        category_id = request.form.get("category_id")
        digest = request.form.get("digest")
        index_image = request.files.get("index_image")
        content = request.form.get("content")
        # 校验参数
        if not all([title, category_id, digest, index_image, content]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        try:
            category_id = int(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        # 提取图片, 将图片上传到七牛云
        try:
            index_image_data = index_image.read()
            key = storage(index_image_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="图片上传失败")
        # 初始化新闻模型并赋值
        news = News()
        news.title = title  # 标题
        news.source = source  # 来源
        news.digest = digest  # 摘要
        news.content = content  # 内容
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key  # 图片路径
        news.category_id = category_id  # 分类id
        news.user_id = user.id  # 作者id
        news.status = 1  # 审核状态
        # 保存数据库
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
        # 返回结果
        return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    """查询收藏新闻"""
    # 获取页数
    page = request.args.get("p", 1)
    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = []
    total_page = 1
    current_page = 1
    # 查询指定页的数据
    try:
        paginate = user.collection_news.paginate(page, 2, False)
        total_page = paginate.pages  # 总页数
        current_page = paginate.page  # 当前页
        news_list = paginate.items  # 分页数据
    except Exception as e:
        current_app.logger.error(e)
    # 获取收藏列表
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    data = {"total_page": total_page,
            "current_page": current_page,
            "collections": news_dict_li}

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    """修改密码"""
    user = g.user
    if request.method == "GET":
        data = {"user_info": user.to_dict()}
        return render_template("news/user_pass_info.html", data=data)
    else:
        # 修改密码
        # 获取参数
        old_password = request.json.get("old_password")
        new_password = request.json.get("new_password")
        # 校验参数
        if not all([old_password, new_password]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        # 判断九密码是否正确
        if not user.check_passowrd(old_password):
            return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
        # 修改密码
        user.password = new_password
        return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    """图像设置"""
    # print("进来了。。。")
    user = g.user
    if request.method == "GET":
        data = {"user_info": user.to_dict()}
        return render_template("news/user_pic_info.html", data=data)
    else:
        # 获取图片
        try:
            avatar = request.files.get("avatar").read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        # 上传图片
        # 使用自己封装的方法
        try:
            key = storage(avatar)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")
        # 保存图片地址
        user.avatar_url = key
        return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    """用户基本信息"""
    # 获取用户登陆信息
    # 获取参数
    # 校验参数
    # 更新并保存数据
    # 返回结果
    if request.method == "GET":
        user = g.user
        data = {"user": user.to_dict()}
        return render_template("news/user_base_info.html", data=data)
    else:
        print(999)
        # 获取参数
        signature = request.json.get("signature")
        nick_name = request.json.get("nick_name")
        gender = request.json.get("gender")
        # 校验参数
        if not all([signature, nick_name, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if gender not in ["MAN", "WOMAN"]:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        # 更新并保存数据
        user = g.user
        user.signature = signature
        user.gender = gender
        user.nick_name = nick_name
        return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        # 表示没有登陆
        return "hhh"
    data = {"user": user.to_dict()}
    return render_template("news/user.html", data=data)